<template>
	<div id="newSemester">
		<div class="breadcrumb">
			<img src="../../../../static/img/attendance_1.png" class="head_img">
			<span class="title" @click="cancel()">考勤设置</span>/ {{actionText}}
		</div>

		<div class="list">
			<div class="list_head">
				<span class="head_name">考勤目标信息</span>
				<el-button class="save" type="primary" @click="save()">保存</el-button>
				<el-button class="cancel" type="primary" @click="cancel()">取消</el-button>
			</div>
			<el-form ref="semesterForm" :model="semesterForm" :rules="rules" label-width="120px">
				<el-form-item label="学期：" prop="semesterId" required>
					<el-select v-model="semesterForm.semesterId" :disabled="isDisabled" class="el-select" placeholder="请选择学期">
						<el-option v-for='item in semesters' :label='item.name' :value='item.sid' :key='item.sid'></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="考勤总次数：" prop="totalCount">
					<el-input v-model="semesterForm.totalCount" type="number" style="width: 120px" class="el-input"></el-input> 次
					<span class="red">&#x3000;更改考勤总次数后，学生打卡的完成情况将随之更改</span>
				</el-form-item>

				<el-form-item label="考勤时间段：" required>
					<el-input v-model="name" placeholder="时间段名称" style="width: 500px" class="el-input"></el-input>
					<br>
					<el-form-item prop="startTime" class="time">
						<el-time-select v-model="startTime" :editable="false" :picker-options="{start: '04:30',step: '00:30',end: endTime || '23:30'}"
						 placeholder="开始时间" class="qizhiDate" @change="validateTime()"></el-time-select>
					</el-form-item>
					至
					<el-form-item prop="endTime" class="time">
						<el-time-select v-model="endTime" :editable="false" :picker-options="{start: startTime || '05:30',step: '00:30',end: '23:30',minTime: startTime}"
						 class="qizhiDate" placeholder="结束时间"></el-time-select>
					</el-form-item>
					<el-button type="primary" @click="addTimeTags()" style="margin-left: 5px;">添加</el-button>
					<div class="effect-time-tag">
						<el-tag :key="tag" v-for="tag in timeTags" :closable="true" style="margin:0 5px;height:auto;font-size:14px;" :close-transition="false"
						 @close="handleClose(tag)">
						 {{tag.name}}  {{tag.startTime}} - {{tag.endTime}}
						</el-tag>
					</div>
				</el-form-item>
				<el-form-item label="最少签到时长：" prop="minTime">
					<el-input v-model="semesterForm.minTime" type="number" style="width: 120px" class="el-input"></el-input> 分钟
					<span class="red">&#x3000;设置每次最少签到时长后，学生在考勤时间内签到至签退不得小于该时长，否则计入无效签到</span>
				</el-form-item>
				<el-form-item label="应用校区：" prop="zones">
					<el-checkbox-group v-model="semesterForm.zones">
						<el-checkbox v-for="item in campusList" :label="item.unid" value="item.unid" :key='item.unid'>{{item.name}}</el-checkbox>
					</el-checkbox-group>
				</el-form-item>
				<el-form-item label="全程监控系统：" prop="monitoring">
					<el-switch v-model="monitoring" on-text="开" off-text="关" :disabled="isDisabled">
					</el-switch>
					<span class="red">&#x3000;考勤监控范围内，能完整地监控学生考勤状况，只有在考勤区域内活动才计入“签到时长”</span>
				</el-form-item>
			</el-form>
		</div>
	</div>
</template>

<script>
	import { mapState, mapActions } from "vuex";

	export default {
		data() {
			let checkMinTime = (rule, value, callback) => {
				if (value > 0) {
					if (Number.isInteger(value * 1)) {
						let now = new Date().format("yyyy/MM/dd");
						// 遍历时间段
						if (this.timeTags.length < 1) {
							callback(new Error("请先设置考勤时间"));
						} else {
							for (let i = 0; i < this.timeTags.length; i++) {
								let startTime = new Date(
									now + " " + this.timeTags[i].startTime
								).getTime();
								let endTime = new Date(
									now + " " + this.timeTags[i].endTime
								).getTime();
								if (value * 1 > (endTime - startTime) / (1000 * 60)) {
									return callback(new Error("最少签到时长必须小于或等于考勤时间时长"));
								}
							}
							callback();
						}
					} else {
						callback(new Error("请输入整数"));
					}
				} else {
					callback(new Error("请正确设置最少签到时长"));
				}
			};
			let checkTotalCount = (rule, value, callback) => {
				if (value > 0) {
					if (Number.isInteger(value * 1)) {
						callback();
					} else {
						callback(new Error("请输入整数"));
					}
				} else {
					callback(new Error("请正确填写考勤总次数"));
				}
			};
			return {
				actionText: "新增考勤目标",
				messageText: "考勤目标新增完成",
				sid: "",
				attendTragetId: "",
				isDisabled: false,
				timeTags: [],
				campusList: [],
				semesters: [],
				name: "",
				startTime: "",
				endTime: "",
				monitoring: false,
				semesterForm: {
					semesterId: "",
					totalCount: "",
					minTime: "",
					zones: []
				},
				rules: {
					semesterId: [{ required: true, message: "请选择学期", trigger: "change" }],
					totalCount: [
						{ required: true, message: "请输入考勤总次数", trigger: "blur" },
						{ validator: checkTotalCount }
					],
					minTime: [
						{ required: true, message: "请设置最少签到时长", trigger: "blur" },
						{ validator: checkMinTime }
					],
					zones: [
						{
							type: "array",
							required: true,
							message: "请选择应用校区",
							trigger: "change"
						}
					]
				}
			};
		},
		mounted() {
			this.getCampus();
			this.getSemesterDetail();

			if (this.$util.getUrlParam("targetId")) {
				this.actionText = "编辑考勤目标";
				this.messageText = "考勤目标编辑完成";
				this.isDisabled = true;
				this.attendTragetId = this.$util.getUrlParam("targetId");
				this.getAttendanceDetail();
			}
		},
		computed: mapState({ user: state => state.user }),
		methods: {
			save() {
				// let url = this.$util.domain + "/campusadminapi/v2/attendance/target/modify";
				let url = this.$util.domain + "/campusadminapi/v3/attendance/target/modify";
				this.$refs.semesterForm.validate(valid => {
					if (valid) {
						this.$http({
							url,
							method: "POST",
							body: JSON.stringify({
								timeslots: this.timeTags,
								unids: this.semesterForm.zones,
								attendanceTarget: {
									id: this.attendTragetId || "",
									times: this.semesterForm.totalCount,
									minDuration: this.semesterForm.minTime,
									fitAll: this.monitoring == true ? 1 : 0,
									sid: parseInt(this.semesterForm.semesterId)
								}
							})
						}).then(response => {
							if (response.data.error == 10000) {
								this.$util.successMsg(this.messageText);
								location.href = "/#/setAttendance";
							} else {
								this.$util.errorMsg(response.data.message);
							}
						});
					} else {
						return false;
					}
				});
			},
			// 验空
			validateNull() {
				if (!this.semesterForm.semesterId) {
					this.$util.errorMsg("未选择学期，请先选择学期");
					return;
				}
				if (!this.semesterForm.totalCount) {
					this.$util.errorMsg("未填写考勤总次数，请输入考勤总次数");
					return;
				}
				if (this.timeTags.length < 1) {
					this.$util.errorMsg("未设置考勤时间，请设置考勤时间");
					return;
				}
				if (!this.semesterForm.minTime) {
					this.$util.errorMsg("未填写签到时长，请设置最少签到时长");
					return;
				}
				if (this.semesterForm.zones.length < 1) {
					this.$util.errorMsg("未选择请用校区，请选择应用校区");
					return;
				}
			},
			// 添加时间段
			addTimeTags() {
				if(!(this.name).trim()){
					return this.$util.errorMsg("考勤时间段名称不能为空",'','warning');
				}
				if (this.startTime && this.endTime) {
					let now = new Date().format("yyyy/MM/dd");
					let startTime = new Date(now + " " + this.startTime).getTime();
					let endTime = new Date(now + " " + this.endTime).getTime();

					if (this.timeTags.length < 1) {
						this.timeTags.push({
							endTime: this.endTime,
							startTime: this.startTime,
							name: this.name.trim()
						});
						this.endTime = "";
						this.startTime = "";
						this.name = "";
					} else {
						for (let i = 0; i < this.timeTags.length; i++) {
							let preStart = new Date(now + " " + this.timeTags[i].startTime).getTime();
							let preEnd = new Date(now + " " + this.timeTags[i].endTime).getTime();
							if (!(startTime >= preEnd || endTime <= preStart)) {
								this.endTime = "";
								this.startTime = "";
								this.name = "";
								this.$util.errorMsg("新增时间段有误，操作失败");
								return;
							}
							if (
								i == this.timeTags.length - 1 &&
								(startTime >= preEnd || endTime <= preStart)
							) {
								this.timeTags.push({
									endTime: this.endTime,
									startTime: this.startTime,
									name: this.name.trim()
								});
								this.endTime = "";
								this.startTime = "";
								this.name = "";
								return;
							}
						}
					}
				} else {
					this.$util.errorMsg("考勤时间段不能为空",'','warning');
				}
			},
			// 删除时间标签
			handleClose(tag) {
				this.timeTags.splice(this.timeTags.indexOf(tag), 1);
			},
			// 时间段验证
			validateTime() {
				let now = new Date().format("yyyy/MM/dd");
				let endTime = new Date(now + " " + this.endTime).getTime();
				let startTime = new Date(now + " " + this.startTime).getTime();
				if (startTime >= endTime) {
					this.endTime = "";
				}
			},
			// 获取考勤目标详情
			getAttendanceDetail() {
				// let url = this.$util.domain + "/campusadminapi/v2/attendance/target/detail";
				let url = this.$util.domain + "/campusadminapi/v3/attendance/target/detail";
				this.$http({
					url,
					method: "GET",
					params: {
						targetId: Number(this.attendTragetId)
					}
				}).then(response => {
					if (response.data.error == 10000) {
						// 考勤目标详情
						let attendanceObj = response.data.data;
						if (attendanceObj) {
							this.timeTags = attendanceObj.periods;
							this.semesterForm.zones = attendanceObj.unids;
							this.semesterForm.semesterId = String(attendanceObj.sid);
							this.monitoring = attendanceObj.fitAll == 1 ? true : false;
							this.semesterForm.totalCount = String(attendanceObj.times);
							this.semesterForm.minTime = String(attendanceObj.minDuration);
						}
					} else {
						this.$util.errorMsg(response.data.message);
					}
				});
			},
			//获取学期列表
			getSemesterDetail() {
				let url = this.$util.domain + "/campusadminapi/v1/tools/semesters";
				this.$http({
					url,
					method: "GET",
				}).then(response => {
					if (response.data.error == 10000) {
						// 学期列表
						let semesterList = response.data.data;
						if (semesterList && semesterList.length > 0) {
							for (let i = 0; i < semesterList.length; i++) {
								this.semesters.push({
									sid: semesterList[i].sid + "",
									name: semesterList[i].semesterName
								});
							}
						}
					}
				});
			},
			//获取所有校区
			getCampus() {
				let url = this.$util.domain + "/campusadminapi/v1/tools/campuszones";
				this.$http({
					url,
					method: "GET"
				}).then(response => {
					if (response.data.error == 10000) {
						let dataList = response.data.data;
						if (dataList && dataList.length > 0) {
							for (let i = 0; i < dataList.length; i++) {
								this.campusList.push({
									unid: dataList[i].unid,
									name: dataList[i].zoneName
								});
							}
						}
					}
				});
			},
			cancel() {
				location.href = "/#/setAttendance";
			}
		}
	};
</script>

<style scoped>
	#newSemester {
		padding-top: 80px;
		height: calc(100% - 100px);
	}

	.title {
		color: #0398ff;
	}

	.red {
		font-size: 12px;
		color: red;
	}

	.effect-time-tag {
		min-height: 120px;
		margin-top: 20px;
		width: 60%;
		padding: 5px;
		box-sizing: border-box;
		border: 1px solid gray;
	}

	.tips {
		color: red;
		font-size: 12px;
		margin-bottom: 15px;
	}

	#newSemester .el-input {
		display: inline-block;
		width: 40%;
		margin-bottom: 10px;
	}

	.time {
		display: inline-block;
		width: 15%;
		min-width: 150px;
	}

	#newSemester .qizhiDate {
		display: inline-block;
		width: 100%;
	}
</style>